<?php
Globals::requireClass('Controller');
Globals::requireClass('Alipay');
Globals::requireModel('User');
Globals::requireTable('Productv3');
Globals::requireTable('Year');
Globals::requireTable('Orderyear');
Globals::requireTable('Code');
Globals::requireTable('User');
Globals::requireTable('Vmoney');
Globals::requireTable('Vlevel');
Globals::requireTable('Months');

class YearController extends Controller
{
	protected $Productv3Table;
	protected $YearTable;
	protected $OrderyearTable;
	protected $CodeTable;
	protected $UserTable;
	protected $VmoneyTable;
	protected $VlevelTable;
	protected $MonthsTable;
	
	public static $defaultConfig = array(
		'viewEnabled'	=> true,
		'layoutEnabled'	=> true,
		'title'			=> null
	);
	
	public function __construct($config = null)
	{
		parent::__construct($config);
		$this->Productv3Table = new Productv3Table($config);
		$this->YearTable = new YearTable($config);
		$this->OrderyearTable = new OrderyearTable($config);
		$this->CodeTable = new CodeTable($config);
		$this->UserTable = new UserTable($config);
		$this->VmoneyTable = new VmoneyTable($config);
		$this->VlevelTable = new VlevelTable($config);
		$this->MonthsTable = new MonthsTable($config);
		dolog(json_encode($_GET));
	}
	
	public function indexAction()
	{
		$this->layout->pageTitle	= "test";
	}
	
	//包年服务列表
	public function skypedataAction(){
	    $uid = $this->getParam('uid');
	    $token = $this->getParam('token');
	    $machine_type = $this->getParam('machine_type');
	    $usermodel = new UserModel($this->config);
	    $uid = $usermodel->getUserBase($uid, $token ,$machine_type);
	    if($uid < 1){
	        echo json_encode(array('returncode'=>'-1','list'=>array()));
	        exit();
	    }
	    
	    $list = array();
	    $data = $this->Productv3Table->listAll(array('status'=>1));
	    foreach ($data as $v){
	        $tmp = array();
	        $tmp['img'] = DOMAIN.$v['img'];
	        $tmp['img'] = str_replace('../', '', $tmp['img']);
	        $tmp['title'] = $v['name'];
	        $tmp['describe'] = empty($v['remark']) ? '' : $v['remark'];
	        $tmp['url'] = empty($v['url']) ? '' : $v['url'];
	        $tmp['pid'] = $v['id'];
	        $tmp['time'] = '';
	        $tmp['vip'] = $v['is_vip'];
	        $tmp['purchased'] = 0;
	        $list[] = $tmp;
	    }
	    
	    $date = date('Y-m-d H:i:s');
	    $y_data = $this->YearTable->listAllWithFields('pid,enddate,type',"uid = {$uid} and enddate > '{$date}'");
	    foreach ($list as $k=>$v){
	        foreach ($y_data as $v2){
	            if($v['pid'] == $v2['pid']){
	                $list[$k]['purchased'] = 1;
	                if($v2['enddate'] > $list[$k]['time']){
	                    $list[$k]['time'] = $v2['enddate'];
	                }
	            }
	        }
	    }
	    
	    echo json_encode(array('returncode'=>'0','list'=>$list));
	    exit();
	}
	
	//包年服务下单
	public function buyskypeAction(){
	    $uid = $this->getParam('uid');
	    $token = $this->getParam('token');
	    $machine_type = $this->getParam('machine_type');
	    $usermodel = new UserModel($this->config);
	    $uid = $usermodel->getUserBase($uid, $token ,$machine_type);
	    if($uid < 1){
	        echo json_encode(array('returncode'=>'-1','orderid'=>'','price'=>0.00,'title'=>''));
	        exit();
	    }
	    
	    $type = $this->getIntParam('type');
	    
	    $time = time();
	    $data = array();
	    $data['orderid'] = substr($time, -9) . mt_rand(10, 99);
	    $data['uid'] = $uid;
	    $data['createtime'] = date('Y-m-d H:i:s');
	    $data['type'] = $type;
	    $data['status'] = 0;
	    
	    $times = $this->getIntParam('time');
	    $months = $this->MonthsTable->getRow(array('months'=>$times,'moneys2'=>$type,'status'=>1));
	    if(empty($months['id'])){
	        echo json_encode(array('returncode'=>'-1','orderid'=>'','price'=>0.00,'title'=>''));
	        exit();
	    }
	    $data['months'] = $times;
	    
	    if($type == 1){
	        $pid = $this->getIntParam('pid');
	        $product = $this->Productv3Table->getRow($pid);
	        
	        $title = $product['name'];
	        
	        $data['pid'] = $pid;
	        //$data['money'] = 0.01;
	        $data['money'] = $months['moneys'];
	    }elseif($type == 2){
	        $title = '激活码X'.$months['months'];
	        
	        $data['pid'] = 0;
	        //$data['money'] = 0.01;
	        $data['money'] = $months['moneys'];
	    }else{
	        echo json_encode(array('returncode'=>'-1','orderid'=>'','price'=>0.00,'title'=>''));
	        exit();
	    }
	    
	    $this->OrderyearTable->add($data);
	    
	    echo json_encode(array('returncode'=>0,'orderid'=>(string)$data['orderid'],'price'=>$data['money'],'title'=>$title));
	    exit();
	}
	
	//包年服务支付成功
	public function buyskypesucceedAction(){
	    $orderid = $this->getParam('orderid');
	    $payorderid = $this->getParam('payorderid');
	    $paytype = $this->getParam('paytype');
	    $sign = $this->getParam('ordersign');
	    /*
	    $new_num_arr = array();
	    $orderid_num = $orderid + 19921206;
	    for ($ii = 0 ; $ii < strlen($orderid_num) ; $ii++){
	        $tmp_num = substr($orderid_num, $ii , 1);
	        $new_num_arr[] = $tmp_num;
	    }
	    krsort($new_num_arr);
	    $new_num = '';
	    foreach ($new_num_arr as $v){
	        $new_num .= (string)$v;
	    }
	    if($sign != $new_num){
	        echo json_encode(array('returncode'=>0,'message'=>'签名错误'));
	        exit();
	    }
	    */
	    $order = $this->OrderyearTable->getRow(array('orderid'=>$orderid));
	    
	    $user = $this->UserTable->getRow($order['uid']);//账号购买者
	    
	    if($user['id'] < 1 || $order['id'] < 1 || $order['status'] != 0){
	        echo json_encode(array('returncode'=>0,'message'=>'订单状态错误'));
	        exit();
	    }
	    
	    $paytypevalue = 0;
	    $paytype = empty($paytype) ? 'alipay' : $paytype;
	    if($paytype == 'alipay'){
	        $alipay = new Alipay();
	        $re = $alipay->queryone('',$payorderid);
	        $alipay_money = $re->response->trade->total_fee;
	        if($order['money'] != $alipay_money){
	            echo json_encode(array('returncode'=>0,'message'=>'支付金额错误'));
	            exit();
	        }
	        
	        $paytypevalue = 1;
	    }elseif($paytype == 'vmoney'){
	        $vcount = 0;
	        $listvalue = $this->VmoneyTable->listAllWithFields('money',array('uid'=>$user['id']));
	        foreach ($listvalue as $k=>$v){
	            $vcount += $v['money'];
	        }
	        if($vcount < $order['money']){
	            echo json_encode(array('returncode'=>0,'message'=>'v币余额不足'));
	            exit();
	        }
	        
	        $paytypevalue = 2;
	    }
	    
	    $date = date('Y-m-d H:i:s');
	    
	    $data['paytype'] = 1;
	    $data['paytime'] = $date;
	    $data['payorderid'] = $payorderid;
	    $data['status'] = 1;
	    $this->OrderyearTable->update($data,$order['id']);
	    
	    $get_money = $order['money'] * 0.05;
	    $get_money = sprintf("%.2f", $get_money);
	    $get_money = $get_money < 0.01 ? 0.01 : $get_money;
	    
	    $user_data['v_money'] = $user['v_money'] + $get_money;
	    $this->UserTable->update($user_data,$order['uid']);
	    
	    if($order['type'] == 1){
	        $product = $this->Productv3Table->getRow($order['pid']);
	        $remark = '购买包月服务获得V币'.$get_money.'，'.$product['name'];
	        $message = $order['monyhs'].'月会员购买成功';
	        
	        $year_data = array();
	        $year_data['pid'] = $product['id'];
	        $year_data['uid'] = $user['id'];
	        $year_data['createdate'] = $date;
	        $year_data['type'] = 1;
	        
	        $year = $this->YearTable->getRow(array('uid'=>$user['id'],'pid'=>$product['id']),'id DESC');
	        $year_data['startdate'] = (isset($year['enddate']) && ($year['enddate'] > $date)) ? $year['enddate'] : $date;
	        $time_tmp = strtotime($year_data['startdate']);
	        $time_tmp = $time_tmp + 86400 * 30 * $order['months'];
	        $year_data['enddate'] = date('Y-m-d H:i:s',$time_tmp);
	        $this->YearTable->add($year_data);
	        
	        if($paytype == 'vmoney'){
	            $user_data['v_money'] = $user_data['v_money'] - $order['money'];
	            $this->UserTable->update($user_data,$order['uid']);
	            
	            $vmoney_data['uid'] = $user['id'];
	            $vmoney_data['type'] = 4;
	            $vmoney_data['money'] = (0-$order['money']);
	            $vmoney_data['remark'] = '购买包月服务消耗V币'.$order['money'];
	            $this->VmoneyTable->add($vmoney_data);
	        }
	    }elseif($order['type'] == 2){
	        $remark = '购买包年服务获得V币'.$get_money.'，激活码';
	        $message = $order['months'].'个激活码购买成功';
	        
	        for ($i=0;$i<$order['months'];$i++){
	            $code_data = array();
	            $code_data['code'] = $user['id'].'a'.$this->create_password(20);
	            $code_data['uid'] = $user['id'];
	            $code_data['createtime'] = $date;
	            $code_data['orderid'] = $order['orderid'];
	            $code_data['status'] = 0;
	            $this->CodeTable->add($code_data);
	        }
	        
	        if($paytype == 'vmoney'){
	            $user_data['v_money'] = $user_data['v_money'] - $order['money'];
	            $this->UserTable->update($user_data,$order['uid']);
	            
	            $vmoney_data['uid'] = $user['id'];
	            $vmoney_data['type'] = 4;
	            $vmoney_data['money'] = (0-$order['money']);
	            $vmoney_data['remark'] = '购买包年服务消耗V币'.$order['money'];
	            $this->VmoneyTable->add($vmoney_data);
	        }
	    }
	    
	    echo json_encode(array('returncode'=>0,'message'=>$message));
	    exit();
	}
	
	protected function create_password($pw_length=10){
	    // 密码字符集，可任意添加你需要的字符
	    $chars = 'abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
	    $password = '';
	    for ( $i = 0; $i < $pw_length; $i++ ){
    	    // 这里提供两种字符获取方式
    	    // 第一种是使用 substr 截取$chars中的任意一位字符；
    	    // 第二种是取字符数组 $chars 的任意元素
    	    // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
    	    $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
	    }
	    return $password;
    }
	
    //激活码列表
    public function cdkeydataAction(){
        $uid = $this->getParam('uid');
        $token = $this->getParam('token');
        $machine_type = $this->getParam('machine_type');
        $usermodel = new UserModel($this->config);
        $uid = $usermodel->getUserBase($uid, $token ,$machine_type);
        if($uid < 1){
            echo json_encode(array('returncode'=>'-1','productlist'=>array(),'codelist'=>array()));
            exit();
        }
        
        $code = array();
        $data = $this->CodeTable->listAll(array('uid'=>$uid));
        foreach ($data as $v){
            $tmp = array();
            $tmp['code'] = $v['code'];
            $tmp['status'] = $v['status'];
            $code[] = $tmp;
        }
        
        $product = array();
        $product_data = $this->Productv3Table->listAll(array('status'=>1,'is_vip'=>1));
        foreach ($product_data as $v){
            $tmp = array();
            $tmp['name'] = $v['name'];
            $tmp['img'] = $v['img'];
            $tmp['pid'] = $v['id'];
            $product[] = $tmp;
        }
        
        echo json_encode(array('returncode'=>'0','productlist'=>$product,'codelist'=>$code));
        exit();   
    }
    
    //使用激活码
    public function usedcdkeyAction(){
        $uid = $this->getParam('uid');
        $token = $this->getParam('token');
        $machine_type = $this->getParam('machine_type');
        $usermodel = new UserModel($this->config);
        $uid = $usermodel->getUserBase($uid, $token ,$machine_type);
        if($uid < 1){
            echo json_encode(array('returncode'=>'0','message'=>'激活码错误或已使用'));
            exit();
        }
        
        $code = $this->getParam('code');
        $pid = $this->getIntParam('pid');
        
        $code_data = $this->CodeTable->getRow(array('code'=>$code,'status'=>0));
        if((int)$code_data['id'] == 0){
            echo json_encode(array('returncode'=>'0','message'=>'激活码错误或已使用'));
            exit();
        }
        
        if($pid < 0){
            echo json_encode(array('returncode'=>'0','message'=>'激活码错误或已使用'));
            exit();
        }
        
        $date_day = date('Y-m-d');
        $count = $this->CodeTable->listCount("used_uid = {$uid} and used_date > '{$date_day}'");
        if($count > 24){
            echo json_encode(array('returncode'=>'0','message'=>'激活码错误或已使用'));
            exit();
        }
        
        $date = date('Y-m-d H:i:s');
        
        $year_data = array();
        $year_data['pid'] = $pid;
        $year_data['uid'] = $uid;
        $year_data['createdate'] = $date;
        $year_data['type'] = 2;
        
        $year = $this->YearTable->getRow(array('uid'=>$uid,'pid'=>$pid),'id DESC');
        $year_data['startdate'] = (isset($year['enddate']) && ($year['enddate'] > $date)) ? $year['enddate'] : $date;
        $time_tmp = strtotime($year_data['startdate']);
        $time_tmp = $time_tmp + 86400 * 30;
        $year_data['enddate'] = date('Y-m-d H:i:s',$time_tmp);
        $this->YearTable->add($year_data);
        
        $this->CodeTable->update(array('status'=>1,'used_uid'=>$uid,'used_date'=>$date,'used_pid'=>$pid),$code_data['id']);
        
        echo json_encode(array('returncode'=>'0','message'=>'激活成功'));
        exit();
    }
    
    //修改链接
    public function skypeurlAction(){
        $uid = $this->getIntParam('uid');
        if($uid < 1){
            echo json_encode(array('returncode'=>'0','url'=>''));
            exit();
        }
        
        $pid = $this->getIntParam('pid');
        //$skypesign = $this->getParam('skypesign');
        $url = $this->getParam('url');
        
        $date = date('Y-m-d H:i:s');
        
        $year_data = $this->YearTable->getRow(" pid = '{$pid}' and uid = '{$uid}' and startdate < '{$date}' and enddate > '{$date}' ");
        if((int)$year_data['id'] == 0){
            echo json_encode(array('returncode'=>'0','url'=>''));
            exit();
        }
        
        $product = $this->Productv3Table->getRow($pid);
        
        //针对芒果tv做处理
        if($product['id'] == 7){
            $newurl = $product['join_url'].str_replace('/#', '', $url).'.html';
        }else{
            $newurl = $product['join_url'].$url;
        }
        
        
        echo json_encode(array('returncode'=>'0','url'=>$newurl));
        exit();
    }
    
    //获得购买时间和价格
    public function timepriceAction(){
        $uid = $this->getParam('uid');
        $token = $this->getParam('token');
        $machine_type = $this->getParam('machine_type');
        $usermodel = new UserModel($this->config);
        $uid = $usermodel->getUserBase($uid, $token ,$machine_type);
        if($uid < 1){
            echo json_encode(array('returncode'=>'0','hinttitle'=>'','list'=>array()));
            exit();
        }
        
        $pid = $this->getIntParam('pid');
        $type = $this->getIntParam('type');
        
        $hinttitle = $type == 1 ? '如无法观看将退还费用！只能在本APP使用！' : '每个激活码可单独激活本APP任意平台！';
        
        $list = array();
        $data = $this->MonthsTable->listAll(array('status'=>1,'moneys2'=>$type));
        foreach ($data as $v){
            $tmp['time'] = $v['months'];
            $tmp['price'] = $v['moneys'];
            $tmp['pid'] = $pid;
            $tmp['type'] = $type;
            $list[] = $tmp;
        }
        
        echo json_encode(array('returncode'=>'0','hinttitle'=>$hinttitle,'list'=>$list));
        exit();
    }
	
	protected function out()
	{
		$this->layout->nav		= 'index';
		parent::out();
	}
}

Config::extend('YearController', 'Controller');
